#!/bin/sh
#
# Starts gateway  .
#
PID_PATH=/var/run/gateway.pid
EXE_PATH=/usr/bin/gateway
OTA_PATH=/root/gateway.update
OLD_PATH=/root/gateway.old


start() {
     printf "Starting gateway sshd: \n"
	#检查是否存在已经下载的最新程序，如果有则进行替换
    #判存
    if [ -f $OTA_PATH ] 
    then
        printf "发现有新程序，开始更新 \n"
        #1 老程序备份
        cp -f $EXE_PATH  $OLD_PATH
        #2 新程序覆盖
        cp -f $OTA_PATH  $EXE_PATH
        #3 给执行权限
        chmod +x $EXE_PATH
    fi

    printf "启动程序\n "
	start-stop-daemon -S -q -p $PID_PATH \
		--exec $EXE_PATH -- daemon
	[ $? = 0 ] && echo "OK" || echo "FAIL"
}
stop() {
	printf "Stopping dropbear sshd: "
	start-stop-daemon -K -q -p $PID_PATH
	[ $? = 0 ] && echo "OK" || echo "FAIL"
}
restart() {
	stop
	start
}

case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart|reload)
  	restart
	;;
  *)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
esac

exit $?